﻿Imports Models.Security
Imports MainLib

Public MustInherit Class BaseService

    Public token As String

    ''' <summary>
    ''' Load token from header
    ''' </summary>
    ''' <param name="request"></param>
    ''' <remarks></remarks>
    Protected Sub loadToken(request As System.Net.Http.HttpRequestMessage)
        If request IsNot Nothing AndAlso request.Headers.Contains("token") Then
            token = request.Headers.GetValues("token").First()
        End If
    End Sub

    ''' <summary>
    ''' Check for access to process by token
    ''' </summary>
    ''' <param name="process"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Function hasAccess(process As String) As Boolean
        Return SessionEngine.getInstance().hasAccess(Me.token, process)
    End Function

    ''' <summary>
    ''' Check for access to proccess and throw exception if not has access.
    ''' </summary>
    ''' <param name="process"></param>
    ''' <remarks></remarks>
    Protected Sub checkAccess(process As String)
        If Not hasAccess(process) Then
            '' TODO: Translate error
            Throw New Exception("access_denied")
        End If
    End Sub

    ''' <summary>
    ''' Get the current client session
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Function getCurrentSession() As ClientSessionVO
        If SessionEngine.getInstance.existsSession(token) Then
            Return SessionEngine.getInstance.getSessionByToken(token).clientSession
        End If

        Return Nothing
    End Function

    Protected Function ExistSession() As Boolean
        Return SessionEngine.getInstance.existsSession(token)
    End Function

End Class